package top.zhangjianyong.blog.config.netty;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ReactorResourceFactory;

/**
 * Netty配置类，用于配置Netty的内存使用
 *
 * @author zhangjianyong
 * @since 2025/7/18
 */
@Slf4j
@Configuration
public class NettyConfig {

  /**
   * 配置ReactorResourceFactory，限制Netty的内存使用
   *
   * @return ReactorResourceFactory
   */
  @Bean
  public ReactorResourceFactory reactorResourceFactory() {
    log.info("初始化ReactorResourceFactory，配置Netty内存限制");
    ReactorResourceFactory factory = new ReactorResourceFactory();

    // 设置为不使用全局资源，这样每个客户端都会有自己的资源
    factory.setUseGlobalResources(false);

    // 设置JVM启动参数，限制Netty的内存使用
    System.setProperty("io.netty.maxDirectMemory", "64MB");
    System.setProperty("io.netty.allocator.maxOrder", "9"); // 2^9 = 512 bytes
    System.setProperty("io.netty.allocator.numHeapArenas", "1");
    System.setProperty("io.netty.allocator.numDirectArenas", "1");
    System.setProperty("io.netty.allocator.tinyCacheSize", "0");
    System.setProperty("io.netty.allocator.smallCacheSize", "0");
    System.setProperty("io.netty.allocator.normalCacheSize", "0");
    System.setProperty("io.netty.allocator.maxCachedBufferCapacity", "0");
    System.setProperty("io.netty.allocator.cacheTrimIntervalMillis", "0");

    return factory;
  }
}
